import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    StyleSheet,
    SafeAreaView,
    Modal,
    ScrollView,
    DeviceEventEmitter
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Constant from '../../utils/Constant'//全局变量
import { getImgUrl, getCarRegisterDate, getMileFormat, getPriceFormat, getStoreStatus, getSaleStatus, getCheckStatus, getPurchaseType } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import Loading from '../../utils/Loading';
import { ToastToUser } from '../../utils/CustomToast';
import GoodsInfoBox from './orderComponents/GoodsInfoBox';
import CarInfoBox from './orderComponents/CarInfoBox';
import BuyerInfoBox from './orderComponents/BuyerInfoBox';
import GuarantePriceBox from './orderComponents/GuarantePriceBox';
import ReceiveAccountBox from './orderComponents/ReceiveAccountBox';
import CommonConfirmPop from '../../components/dialog/CommonConfirmPop';

let navigation = null
/**
 * 卖家订单确认
 */
export default class StartOrderPage extends Component {

    constructor(props) {
        super(props);
        let carId = this.props.route && this.props.route.params && this.props.route.params.carId ? this.props.route.params.carId : '';
        let merchantId = this.props.route && this.props.route.params && this.props.route.params.merchantId ? this.props.route.params.merchantId : '';
        let quotationRecordId = this.props.route && this.props.route.params && this.props.route.params.quotationRecordId ? this.props.route.params.quotationRecordId : '';
        let buyerMerchantName = this.props.route && this.props.route.params && this.props.route.params.buyerMerchantName ? this.props.route.params.buyerMerchantName : '';
        this.state = {
            carId,
            merchantId,
            quotationRecordId,
            quotationPrice: '',
            quotationRecordStatus: '',//报价状态(缺省空表示未报价) 1已报价 2报价已确认 3已下单、4已作废	
            carInfo: {},
            quotationData: {},
            sendAddress: '',//发货地址
            sendName: '',//发货人
            sendPhone: '',//发货人电话
            receivePaymentAccountName: '',//收款账户名称
            receivePaymentBank: '',//收款银行
            receivePaymentBankAccount: '',//收款银行账号
            receivePaymentBankId: '',//银行账号id
            sellerReceiveSubBank: '',//收款银行开户行

            buyerMerchantName: buyerMerchantName,
            isCanEditPrice: false,
            merchantInfo: {},
            areaInfo: null,
            dialogVisible: false,
            type: '',

            // 是否免除服务费
            isServiceFee: 0,

        };
    }

    componentDidMount() {
        this.getCarDetails()

        // if (this.state.quotationRecordId != '') {
        //     this.getByquotationRecordId()
        // } else {
        //     // this.getQuotationByCarId()
        // }

        this.getOwnCompanyInfo()
        this.getBankCardList()

        this.nowLoginUserDetail()
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                {/* 顶部导航栏 */}
                <Header navigation={navigation} Title={'确认订单'} bgColor={'#ffffff'} ></Header>

                <ScrollView style={{ flex: 1, paddingHorizontal: 8 }} showsVerticalScrollIndicator={false}>

                    {/* 发货信息 */}
                    <GoodsInfoBox
                        title={'发货信息'}
                        navigation={this.props.navigation}
                        sendAddress={this.state.sendAddress}
                        sendName={this.state.sendName}
                        sendPhone={this.state.sendPhone}
                        merchantInfo={this.state.merchantInfo}
                        onConfirm={(result, name, phone, areaInfo) => {
                            console.log('areaInfo', areaInfo)
                            this.setState({
                                sendAddress: result,
                                sendName: name,
                                sendPhone: phone,
                                areaInfo: areaInfo
                            })
                        }}
                    />

                    {/* 车辆信息 */}
                    <CarInfoBox
                        quotationPrice={0}
                        carInfo={this.state.carInfo} />

                    {/* 买家信息 */}
                    <BuyerInfoBox
                        navigation={this.props.navigation}
                        isCanEditPrice={this.state.isCanEditPrice}
                        buyerMerchantName={this.state.buyerMerchantName}
                        quotationData={this.state.quotationData}
                        quotationPrice={this.state.quotationPrice}
                        onConfirm={(result) => {
                            console.log('jiage', result)
                            let price = result  * 100
                            this.setState({
                                quotationPrice: price,

                            })
                            this.quotationCalculateAmount(price)
                        }}
                        onServiceFeeChange={(result) => {
                            console.log('onServiceFeeChange', result)
                            this.setState({
                                isServiceFee: result
                            })
                        }}
                    />

                    {/* 保证金 */}
                    <GuarantePriceBox
                        quotationData={this.state.quotationData} />

                    {/* 收款账户 */}
                    <ReceiveAccountBox
                        isShowModify={true}
                        receivePaymentBank={this.state.receivePaymentBank}
                        receivePaymentBankAccount={this.state.receivePaymentBankAccount}
                        receivePaymentAccountName={this.state.receivePaymentAccountName}
                        receivePaymentBankId={this.state.receivePaymentBankId}
                        navigation={this.props.navigation}
                        completion={(result) => {
                            console.log(result)
                            this.setState({
                                receivePaymentBank: result.accountBank,
                                receivePaymentBankAccount: result.accountNo,
                                receivePaymentAccountName: result.accountName,
                                receivePaymentBankId: result.id,
                                sellerReceiveSubBank:result.subBank
                            })
                        }}
                    />

                    <Text style={styles.desText}>*请确认发车地址及报价金额，确认后交易锁定，最终交易金额请在出具自检报告后与买家确定。</Text>

                </ScrollView>

                {/* 底部按钮 */}
                {this.renderBottomBtn()}

                {this.state.dialogVisible ?
                    <CommonConfirmPop
                        visible={this.state.dialogVisible}
                        content={'当前账户保证金可用余额不足以担保此车辆交易，请先补充足够保证金。'}
                        des={'例：1万保证金可担保5万车价'}
                        onClose={() => {
                            this.setState({
                                dialogVisible: false
                            })

                        }}
                        onCancel={() => {
                            this.setState({
                                dialogVisible: false
                            })
                            if (this.state.type == 1) {//发送确认
                                this.quotationSellerInitiate()
                            } else {
                                this.confirmOfferPrice()
                            }
                        }}
                        onSure={() => {
                            this.setState({
                                dialogVisible: false
                            })
                            navigation.navigate('BondAccountPage', {})
                        }}
                        sureText={'去充值'}
                        cancelText={'继续确认'}

                    >

                    </CommonConfirmPop>
                    :
                    null
                }
                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        );
    }

    /**
     * 已报价 显示【驳回报价】、【发送确认】
     * 未报价或者被驳回 显示【发送订单】
     * 加盟商已确认报价，或直接发送了订单，联盟商家未确认订单的情况下，加盟商可【取消订单】。
     * @returns 
     */
    renderBottomBtn() {
        return (
            <View style={[styles.bottomBox, { height: 50 + Constant.bottomHeight }]}>

                {this.state.quotationRecordStatus == 0 || (this.state.quotationRecordStatus == 1 && this.state.quotationData && this.state.quotationData.historyRO
                    && this.state.quotationData.historyRO.isReject == 1) || this.state.quotationRecordStatus == 4 ?
                    <TouchableOpacity
                        activeOpacity={0.8}
                        style={styles.bottomRightItemBox}
                        onPress={() => {
                            // this.quotationSellerInitiate()
                            this.setState({ type: 1 })
                            this.checkAndFetchMerchantBalance(1)
                        }}
                    >
                        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
                            colors={['#FFEF3A', '#FFDB1B']}
                            style={styles.itemInnerBox}>
                            <Text style={styles.bottomRightItemText}>发送订单</Text>

                        </LinearGradient>
                    </TouchableOpacity>
                    :
                    this.state.quotationRecordStatus == 1 ?

                        <View style={styles.bottomBox1}>
                            <TouchableOpacity
                                activeOpacity={0.8}
                                style={styles.bottomLeftItemBox}
                                onPress={() => {
                                    this.quotationReject()
                                }}
                            >
                                <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
                                    colors={['#F5F5F5', '#F5F5F5']}
                                    style={styles.itemInnerBox}
                                >
                                    <Text style={styles.bottomRightItemText1}>驳回报价</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                            <TouchableOpacity
                                activeOpacity={0.8}
                                style={styles.bottomRightItemBox1}
                                onPress={() => {
                                    this.setState({ type: 2 })
                                    this.checkAndFetchMerchantBalance(2)
                                    // this.confirmOfferPrice()
                                }}
                            >
                                <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
                                    colors={['#FFEF3A', '#FFDB1B']}
                                    style={styles.itemInnerBox}>
                                    <Text style={styles.bottomRightItemText}>发送确认</Text>

                                </LinearGradient>
                            </TouchableOpacity>
                        </View>
                        :
                        null

                }
                {this.state.quotationRecordStatus == 2 ?
                    <TouchableOpacity
                        activeOpacity={0.8}
                        style={styles.bottomLeftItemBox}
                        onPress={() => {
                            this.cancelOrder()
                        }}
                    >
                        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
                            colors={['#F5F5F5', '#F5F5F5']}
                            style={styles.itemInnerBox}
                        >
                            <Text style={styles.bottomRightItemText1}>取消订单</Text>
                        </LinearGradient>
                    </TouchableOpacity>
                    :
                    null
                }

            </View>
        )
    }



    getSubCarInfo(item) {

        let carInfoStr = ''
        if (item.registerDate && item.registerDate != null) {
            carInfoStr = getCarRegisterDate(item.registerDate)
        }

        if (item.mileage && item.mileage != 0) {
            carInfoStr = carInfoStr + ' | ' + getMileFormat(item.mileage)
        }

        if (item.cityName && item.cityName != '') {
            if (carInfoStr != '') {
                carInfoStr = carInfoStr + ' | ' + item.cityName
            } else {
                carInfoStr = item.cityName
            }

        }

        return carInfoStr
    }

    setShowConfirmModal(isShow) {
        this.setState({
            showConfirmModal: isShow
        })
    }

    getCarDetails() {
        let param = {
            carId: this.state.carId,
            merchantId: this.state.merchantId
        }
        if (this.Loading) {
            this.Loading.show();
        }

        HttpUtils.getRequest(HttpUrls.getOthersCarDetails, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let data = result.data
                this.setState({
                    carInfo: data
                })

                this.getByquotationRecordId()
                l
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    nowLoginUserDetail() {
        HttpUtils.getRequest(HttpUrls.nowLoginUserDetail)
            .then((result) => {

                if (result.code == 0) {
                    this.setState({
                        sendPhone: result.data?.phone || '',
                        sendName: result.data?.fullname || ''
                    })
                }
            })
            .catch((error) => {
            });
    }

    getOwnCompanyInfo() {

        let param = {
            merchantId: Constant.userInfo.merchantId,
        }
        HttpUtils.getRequest(HttpUrls.getMerchantDetail, param)
            .then((result) => {

                if (result.code == 0) {
                    let data = result.data
                    this.setState({
                        sendAddress: data.address,
                        // sendPhone: data.phone,
                        // sendName: data.owner,
                        // receivePaymentBank: data.accountBank,
                        // receivePaymentBankAccount: data.accountNo,
                        // receivePaymentAccountName: data.accountName,
                        merchantInfo: data
                    })
                }
            })
            .catch((error) => {

            });
    }

    getBankCardList() {


        let param = {
            merchantId: Constant.userInfo.merchantId,
        }
        HttpUtils.getRequest(HttpUrls.getFinanceInfoList, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    data.map((item, index) => {
                        if (item.isDefault == 1) {
                            this.setState({
                                receivePaymentBank: item.accountBank,
                                receivePaymentBankAccount: item.accountNo,
                                receivePaymentAccountName: item.accountName,
                                receivePaymentBankId: item.id,
                                sellerReceiveSubBank: item.subBank
                            })
                        }
                    })
                }
            })
            .catch((error) => {

            });
    }

    getQuotationByCarId() {
        let param = {
            carId: this.state.carId
        }
        HttpUtils.getRequest(HttpUrls.getQuotationByCarId, param)
            .then((result) => {
                if (result.data) {
                    this.setState({
                        quotationData: result.data
                    })
                }
            })
            .catch((error) => {

            });
    }

    getByquotationRecordId() {
        let param = {

            quotationRecordId: this.state.quotationRecordId
        }

        HttpUtils.getRequest(HttpUrls.getByquotationRecordId, param)
            .then((result) => {
                if (result.data) {
                    this.setState({
                        quotationData: result.data,
                        quotationRecordStatus: result.data.quotationRecordStatus,
                        quotationPrice: result.data.quotationPrice
                    })
                    if (result.data.quotationRecordStatus == 0 || (result.data.quotationRecordStatus == 1 && result.data && result.data.historyRO
                        && result.data.historyRO.isReject == 1) || result.data.quotationRecordStatus == 4) {

                        this.setState({
                            isCanEditPrice: true
                        })
                    } else {
                        this.setState({
                            isCanEditPrice: false
                        })
                    }

                    if (!result.data.quotationPrice) {
                        this.setState({
                            quotationPrice: this.state.carInfo.listPrice * 100
                        })
                        this.quotationCalculateAmount(this.state.carInfo.listPrice * 100)
                    }


                }

            })
            .catch((error) => {

            });
    }

    quotationCalculateAmount(quotationPrice) {


        let param = {
            quotationPrice: quotationPrice,
        }
        HttpUtils.postRequest(HttpUrls.quotationCalculateAmount, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    let quotationData = this.state.quotationData
                    quotationData.advancePayment = data.advancePayment
                    quotationData.carDeposit = data.carDeposit
                    quotationData.contractDeposit = data.contractDeposit
                    quotationData.detectionFee = data.detectionFee
                    quotationData.tailPayment = data.tailPayment
                    quotationData.tradePrice = data.tradePrice

                    this.setState({
                        quotationData: quotationData
                    })

                }
            })
            .catch((error) => {

            });
    }

    checkAndFetchMerchantBalance(type) {

        let params = {
            merchantId: Constant.userInfo.merchantId,
            quotationAmount: this.state.quotationPrice
        }
        this.Loading.show('保证金查询中...')
        HttpUtils.getRequest(HttpUrls.checkAndFetchMerchantBalance, params).then(result => {
            this.Loading.hide()
            if (result.code == 0) {
                if (result.data) {
                    if (type == 1) {//发送确认
                        this.quotationSellerInitiate()
                    } else {
                        this.confirmOfferPrice()
                    }
                } else {
                    this.setState({
                        dialogVisible: true
                    })
                }

            } else {
                ToastToUser(result.msg ? result.msg : result.statusText + '')
            }
        }).catch(err => {
            this.Loading.hide()
        })
    }


    confirmOfferPrice() {
        let param = {

            quotationRecordId: this.state.quotationRecordId,
            sellerReceiveId: this.state.receivePaymentBankId,
            sellerReceiveBankName: this.state.receivePaymentBank,
            sellerReceiveBankAccount: this.state.receivePaymentBankAccount,
            sellerReceiveAccountName: this.state.receivePaymentAccountName,
            sellerReceiveSubBank: this.state.sellerReceiveSubBank,
            sellerShipperName: this.state.sendName,
            sellerShipperPhone: this.state.sendPhone,
            sellerShipperAddress: this.state.sendAddress
        }

        if (this.state.areaInfo == null) {
            param.sellerShipperProvince = this.state.merchantInfo.province
            param.sellerShipperCity = this.state.merchantInfo.city
            param.sellerShipperDistrict = this.state.merchantInfo.district
            param.sellerShipperProvinceName = this.state.merchantInfo.provinceName
            param.sellerShipperCityName = this.state.merchantInfo.cityName
            param.sellerShipperDistrictName = this.state.merchantInfo.districtName
        } else {
            param.sellerShipperProvince = this.state.areaInfo.province
            param.sellerShipperCity = this.state.areaInfo.city
            param.sellerShipperDistrict = this.state.areaInfo.area
            param.sellerShipperProvinceName = this.state.areaInfo.provinceName
            param.sellerShipperCityName = this.state.areaInfo.cityName
            param.sellerShipperDistrictName = this.state.areaInfo.areaName
        }

        this.Loading.show('确认报价中...')
        HttpUtils.postRequest(HttpUrls.quotationSellerConfirm, param)
            .then((result) => {
                this.Loading.hide()
                if (result.code == 0) {
                    ToastToUser('确认报价成功')
                    DeviceEventEmitter.emit('commonEvent', { type: 'offerPriceConfrimSuccess' })
                    setTimeout(() => {
                        navigation.goBack()
                    }, 1000);
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }

            })
            .catch((error) => {
                this.Loading.hide()
            });
    }


    quotationSellerInitiate() {
        let param = {

            quotationRecordId: this.state.quotationRecordId,
            sellerReceiveId: this.state.receivePaymentBankId,
            sellerReceiveBankName: this.state.receivePaymentBank,
            sellerReceiveBankAccount: this.state.receivePaymentBankAccount,
            sellerReceiveAccountName: this.state.receivePaymentAccountName,
            sellerReceiveSubBank: this.state.sellerReceiveSubBank,
            sellerShipperName: this.state.sendName,
            sellerShipperPhone: this.state.sendPhone,
            sellerShipperAddress: this.state.sendAddress,
            quotationPrice: this.state.quotationPrice,

            noServiceFee: this.state.isServiceFee,
            carId: this.state.carId,

        }
        if (this.state.areaInfo == null) {
            param.sellerShipperProvince = this.state.merchantInfo.province
            param.sellerShipperCity = this.state.merchantInfo.city
            param.sellerShipperDistrict = this.state.merchantInfo.district
            param.sellerShipperProvinceName = this.state.merchantInfo.provinceName
            param.sellerShipperCityName = this.state.merchantInfo.cityName
            param.sellerShipperDistrictName = this.state.merchantInfo.districtName
        } else {
            param.sellerShipperProvince = this.state.areaInfo.province
            param.sellerShipperCity = this.state.areaInfo.city
            param.sellerShipperDistrict = this.state.areaInfo.area
            param.sellerShipperProvinceName = this.state.areaInfo.provinceName
            param.sellerShipperCityName = this.state.areaInfo.cityName
            param.sellerShipperDistrictName = this.state.areaInfo.areaName
        }

        console.log(param, 'eeeee')

        this.Loading.show('确认报价中...')
        HttpUtils.postRequest(HttpUrls.quotationSellerInitiate, param)
            .then((result) => {
                this.Loading.hide()
                if (result.code == 0) {
                    ToastToUser('确认报价成功')
                    DeviceEventEmitter.emit('commonEvent', { type: 'offerPriceConfrimSuccess' })
                    navigation.goBack()
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }

            })
            .catch((error) => {
                this.Loading.hide()
            });
    }

    quotationReject() {
        let params = {
            quotationRecordId: this.state.quotationRecordId
        }
        this.Loading.show('驳回中...')
        HttpUtils.postRequest(HttpUrls.quotationReject, params).then(result => {
            this.Loading.hide()
            if (result.code == 0) {
                ToastToUser('驳回成功')
                setTimeout(() => {
                    navigation.goBack()
                }, 1000);
            } else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        }).catch(err => {
            this.Loading.hide()
        })
    }


    cancelOrder() {
        let params = {
            quotationRecordId: this.state.quotationRecordId
        }
        HttpUtils.postRequest(HttpUrls.quotationCancel, params).then(result => {

            if (result.code == 0) {
                ToastToUser('取消成功')
                navigation.goBack()
            } else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        }).catch(err => {

        })
    }



};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    desText: {
        marginVertical: 10,
        color: '#ED542E',
        fontSize: 14,
        lineHeight: 20,
    },
    bottomBox: {
        width: '100%',
        flexDirection: 'row',
        alignItems: 'flex-start',
        justifyContent: 'flex-end',
        backgroundColor: '#fff',
        paddingHorizontal: 16,
        borderTopColor: '#e4e4e4',
        borderTopWidth: 0.5
    },
    bottomBox1: {
        width: '100%',
        height: 50,
        flexDirection: 'row',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
    },
    bottomLeftItemBox: {
        marginTop: 12,
        flex: 1.2,
        height: 36,
    },

    bottomRightItemBox: {
        marginTop: 12,
        width: 140,
        height: 36,
    },
    bottomRightItemBox1: {
        marginLeft: 15,
        marginTop: 12,
        flex: 1.8,
        height: 36,
    },
    itemInnerBox: {
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 18,

    },
    bottomRightItemText: {
        color: '#222',
        fontSize: 14,
    },
    bottomRightItemText1: {
        color: '#222',
        fontSize: 14,
    }
});
